/**
 * Created by zhanglihe on 15/9/9.
 */
require.config(require_config);

define([
    'jquery',
    'common',
    'ready',
    'template',
    'model',
    'dialog'
], function ($, common, ready, template, Model, dialog) {

    var index = function () {
        this.init();
    };
    index.prototype = {
        init: function () {
            var _this = this;
            var id = getUrlPath(4);
            $.ajax({
                url: _global.url.api + 'shipping/' + id,
                type: 'get',
                async: false,
                success: function (res) {
                    if (res.code == 0) {
                        _this.set('shipping', res.data);
                    }
                }
            });
            $.ajax({
                url: _global.url.api + 'regions',
                type: 'get',
                async: false,
                data: {depth: 3},
                success: function (res) {
                    if (res.code == 0) {
                        _this.set('region', res.data);
                    }
                }
            });
            this.fetch();
        },

        fetch: function () {
            var _this = this;
            var id = getUrlPath(4);
            $('#add-form').html(template('main_tpl', {region: this.region, shipping: this.shipping}));
            if (this.shipping.area_fees) {
                $.each(this.shipping.area_fees, function (i, val) {
                    var html = template("model_tpl", {val: val});
                    $("#data-list").append(html);
                    $(".item-del").on("click", function (e) {
                        e.preventDefault();
                        $(this).parents('tr').remove();
                    });
                    $(".weight1").blur(function (e) {
                        check_type($(this), $(this).val());
                    });
                    $(".fee1").blur(function (e) {
                        check_type($(this), $(this).val());
                    });
                    $(".weight2").blur(function (e) {
                        check_type($(this), $(this).val());
                    });
                    $(".fee2").blur(function (e) {
                        check_type($(this), $(this).val());
                    });
                });
            }
            if (this.shipping.origin_province != 0 && this.shipping.origin_province) {
                var city = _this.region[this.shipping.origin_province].child;

                for (var n in city) {
                    if (city[n].id == this.shipping.origin_city) {
                        $('select[name="origin_city"]').append('<option value="' + city[n].id + '" selected="selected">' + city[n].name + '</option>');
                    } else {
                        $('select[name="origin_city"]').append('<option value="' + city[n].id + '" >' + city[n].name + '</option>');
                    }

                }
            }

            if (this.shipping.is_free == 1) {
                $(".free_baoyou_show").hide();
                $(".derate_rules_type13").hide();
            } else {
                $(".free_baoyou_show").show();
            }
            if (this.shipping.derate_rules_type == 1) {
                $(".derate_rules_type13").show();
            } else {
                $(".derate_rules_type13").hide();
            }
            if (this.shipping.charge_mode == 1) {
                $(".show_danwei").html("件");
                $(".show_danweis").html("首件(件)");
                $(".show_danweiss").html("续件(件)");
            } else {
                $(".show_danwei").html("Kg");
                $(".show_danweis").html("首重(Kg)");
                $(".show_danweiss").html("续重(Kg)");
            }


            _this.event();
            this.model = new Model({
                url: _global.url.api + 'shipping/' + id,
                data: {}
            });
        },
        set: function ($k, $v) {
            this[$k] = $v;
        },
        event: function (e) {
            var _this = this;

            // 区域全选,反选
            $('body').on('click', '#area_all', function () {
                var checkboxList = $('#province_list :checkbox');
                $.each(checkboxList, function (index, value) {
                    if (!$(value).attr('disabled')) {
                        $(value).prop('checked', true);
                    }
                });
            });

            $('body').on('click', '#area_rever', function () {
                var checkboxList = $('#province_list :checkbox');
                checkboxList.each(function (index, value) {
                    if (!$(value).attr('disabled')) {
                        var isChecked = $(value).prop("checked");
                        $(value).prop("checked", !isChecked);
                    }

                });
            });

            $('#origin_province').on('change', function (e) {
                $('select[name="origin_city"]').html('');
                var id = $(this).val();
                var city = _this.region[id].child;
                for (var n in city) {
                    $('select[name="origin_city"]').append('<option value="' + city[n].id + '">' + city[n].name + '</option>')
                }
            });
            $("input[name='is_area_limited']").on("click", function (e) {
                //e.preventDefault();
                if ($(this).val() == 1) {
                    $(".area_select").show();
                } else {
                    $(".area_select").hide();
                }
            });
            $("input[name='is_free']").on("click", function (e) {
                if ($(this).val() == 1) {
                    $(".free_baoyou_show").hide();
                } else {
                    $(".free_baoyou_show").show();
                }
            });
            $("#derate_rules_type").on("change", function (e) {
                if ($(this).val() == 1) {
                    $(".rules_type").html("满金额");
                    $(".rules_danwei").html("元");
                    $(".derate_rules_type13").show();
                    $(".derate_rules_type2").hide();
                } else if ($(this).val() == 2) {
                    $(".derate_rules_type13").hide();
                    $(".derate_rules_type2").show();
                } else if ($(this).val() == 3) {
                    $(".rules_type").html("满件数/重量");
                    $(".rules_danwei").html("件/kg");
                    $(".derate_rules_type13").show();
                    $(".derate_rules_type2").hide();
                }
                else {
                    $(".derate_rules_type13").hide();
                    $(".derate_rules_type2").hide();
                }
            });
            $("input[name='charge_mode']").on("click", function (e) {
                //e.preventDefault();
                if ($(this).val() == 1) {
                    $(".show_danwei").html("件");
                    $(".show_danweis").html("首件(件)");
                    $(".show_danweiss").html("续件(件)");
                } else {
                    $(".show_danwei").html("Kg");
                    $(".show_danweis").html("首重(Kg)");
                    $(".show_danweiss").html("续重(Kg)");
                }
            });
            $("#rules_value").blur(function () {
                var rules_value = $.trim($(this).val());
                var reg = /^[0-9]+(\.[0-9]{1,2})?$/;
                if (rules_value != "") {
                    if (!reg.test(rules_value)) {
                        Alert({msg: "输入格式不正确", type: 'error'});
                        $(this).val("");
                        return false;
                    }
                }
            });
            $("#item-add").on("click", function (e) {
                e.preventDefault();
                var w1 = $("input[name='weight1']").val();
                var f1 = $("input[name='fee1']").val();
                var w2 = $("input[name='weight2']").val();
                var f2 = $("input[name='fee2']").val();
                if (!check_add(w1, f1, w2, f2)) {
                    return false;
                }
                ;
                var html = template("model_tpl_edit");
                $("#data-list").append(html);
                $(".item-del").on("click", function (e) {
                    e.preventDefault();
                    $(this).parents('tr').remove();
                });
                $(".select_area").on("click", function (e) {
                    e.preventDefault();
                    var dom = $(this);
                    var region = new Array();
                    $(this).parent().find(".area_lists a").each(function () {
                        region.push($(this).find('input').attr("id"));
                    });
                    var regions = ',' + region.join(',') + ',';
                    set_arae(e, dom, _this.region, regions);
                });
                $(".weight1").blur(function (e) {
                    check_type($(this), $(this).val());
                });
                $(".fee1").blur(function (e) {
                    check_type($(this), $(this).val());
                });
                $(".weight2").blur(function (e) {
                    check_type($(this), $(this).val());
                });
                $(".fee2").blur(function (e) {
                    check_type($(this), $(this).val());
                });
            });

            $("#select_area").on("click", function (e) {
                e.preventDefault();
                var region = new Array();
                $("#area_list a").each(function () {
                    region.push($(this).find('input').attr("id"));
                });
                var regions = ',' + region.join(',') + ',';
                var areas_select = '';
                var content = template('region-tpl', {
                    region: _this.region,
                    regions: regions,
                    areas_select: areas_select
                });
                var area = new Array();
                dialog({
                    id: 'province-list',
                    content: content,
                    width: 500,
                    ok: function () {
                        $('#area_list').html('');
                        $('input[name="area_id"]').each(function () {
                            if ($(this).is(':checked')) {
                                area.push($(this).attr('id'));
                                var item = '<a href="#">' + $(this).val() + '<input type="hidden" name="area_item" id="' + $(this).attr('id') + '" value="' + $(this).val() + '"/> </a> , ';
                                $('#area_list').append(item);
                                $("#area_filter").val(area.join(','));
                            }
                        });
                    },
                    cancel: function () {

                    }
                }).show();
            });
            $("#select_area_rule").on("click", function (e) {
                e.preventDefault();
                var region = new Array();
                $("#area_list a").each(function () {
                    region.push($(this).find('input').attr("id"));
                });
                var regions = ',' + region.join(',') + ',';
                var areas_select = '';
                var content = template('region-tpl', {
                    region: _this.region,
                    regions: regions,
                    areas_select: areas_select
                });
                var area = new Array();
                dialog({
                    id: 'province-list',
                    content: content,
                    width: 500,
                    ok: function () {
                        $('#area_list_rule').html('');
                        $('input[name="area_id"]').each(function () {
                            if ($(this).is(':checked')) {
                                area.push($(this).attr('id'));
                                var item = '<a href="#">' + $(this).val() + '<input type="hidden" name="area_item" id="' + $(this).attr('id') + '" value="' + $(this).val() + '"/> </a> , ';
                                $('#area_list_rule').append(item);
                                $("#area_filter_rule").val(area.join(','));
                            }
                        });
                    },
                    cancel: function () {

                    }
                }).show();
            });
            $(".select_area").on("click", function (e) {
                e.preventDefault();
                var dom = $(this);
                var region = new Array();
                $(this).parent().find(".area_lists a").each(function () {
                    region.push($(this).find('input').attr("id"));
                });
                var regions = ',' + region.join(',') + ',';
                set_arae(e, dom, _this.region, regions);
            });
            $("#btn_save_add").off().on("click", function (e) {
                _this.model.data.name = $.trim($("#name").val());
                if (_this.model.data.name == '') {
                    Alert({msg: "请输入模板名称", type: 'error'});
                    return false;
                }
                _this.model.data.origin_province = $("#origin_province").val();
                if (_this.model.data.origin_province == '--请选择--') {
                    Alert({msg: "请选择发货省份", type: 'error'});
                    return false;
                }
                _this.model.data.origin_city = $("#origin_city").val();
                if (_this.model.data.origin_city == '--请选择--') {
                    Alert({msg: "请选择发货城市", type: 'error'});
                    return false;
                }
                _this.model.data.delivery_within = $("#delivery_within").val();
                if (_this.model.data.delivery_within == '') {
                    Alert({msg: "请输入发货时间", type: 'error'});
                    return false;
                }
                _this.model.data.is_free = $("input[name='is_free']:checked").val();
                _this.model.data.charge_mode = $("input[name='charge_mode']:checked").val();
                _this.model.data.is_area_limited = $("input[name='is_area_limited']:checked").val();
                _this.model.data.area_filter = $("#area_filter").val();
                if (_this.model.data.is_area_limited == 1) {
                    if (_this.model.data.area_filter == '') {
                        Alert({msg: "请选择要限制的区域", type: 'error'});
                        return false;
                    }
                }
                _this.model.data.derate_rules_type = $("#derate_rules_type").val();
                if (_this.model.data.derate_rules_type == '--请选择--') {
                    _this.model.data.derate_rules_type = '';
                }
                if (_this.model.data.derate_rules_type == 1) {
                    _this.model.data.rules_value = $.trim($("#rules_value").val());
                    if (_this.model.data.rules_value == "") {
                        Alert({msg: "请输入满减金额", type: 'error'});
                        return false;
                    }
                }
                if (_this.model.data.derate_rules_type == 2) {
                    _this.model.data.area_filter_rule = $("#area_filter_rule").val();
                    if (_this.model.data.area_filter_rule == '') {
                        Alert({msg: "请选择满减的地区", type: 'error'});
                        return false;
                    }
                }
                if (_this.model.data.derate_rules_type == 3) {
                    _this.model.data.rules_value = $.trim($("#rules_value").val());
                    if (_this.model.data.rules_value == "") {
                        Alert({msg: "请输入满减件数/重量", type: 'error'});
                        return false;
                    }
                }
                if (_this.model.data.is_free != 1) {
                    _this.model.data.weight1 = $("#weight1").val();
                    if (_this.model.data.weight1 == '') {
                        Alert({msg: "请输入默认重量", type: 'error'});
                        return false;
                    }
                    _this.model.data.fee1 = $("#fee1").val();
                    if (_this.model.data.fee1 == '') {
                        Alert({msg: "请输入默认运费", type: 'error'});
                        return false;
                    }
                    _this.model.data.weight2 = $("#weight2").val();
                    if (_this.model.data.weight2 == '') {
                        Alert({msg: "请输入续增重量", type: 'error'});
                        return false;
                    }
                    _this.model.data.fee2 = $("#fee2").val();
                    if (_this.model.data.fee2 == '') {
                        Alert({msg: "请输入续增运费", type: 'error'});
                        return false;
                    }
                    var areas = new Array();
                    var lag = true;
                    $(".areas").each(function () {
                        if ($(this).val() == '') {
                            lag = false;
                            return false;
                        } else {
                            areas.push($(this).val());
                            lag = true;
                        }

                    });
                    if (!lag) {
                        Alert({msg: "请选择运送的城市", type: 'error'});
                        return false;
                    }
                    var areas_str = areas.join("*");
                    _this.model.data.areas_str = areas_str;
                    var weight1s = new Array();
                    var lwighs = true;
                    $("input[name='weight1']").each(function () {
                        if ($(this).val() == '') {
                            lwighs = false;
                            return false;
                        } else {
                            weight1s.push($(this).val());
                            lwighs = true;
                        }

                    });
                    if (!lwighs) {
                        Alert({msg: "请输入首重量", type: 'error'});
                        return false;
                    }
                    _this.model.data.weight1s_str = weight1s.join("*");
                    var fee1s = new Array();
                    var lfeds = true;
                    $("input[name='fee1']").each(function () {
                        if ($(this).val() == '') {
                            lfeds = false;
                            return false;
                        } else {
                            fee1s.push($(this).val());
                            lfeds = true;
                        }

                    });
                    if (!lfeds) {
                        Alert({msg: "请输入首运费", type: 'error'});
                        return false;
                    }
                    _this.model.data.fee1s_str = fee1s.join("*");
                    var weight2s = new Array();
                    var lw = true;
                    $("input[name='weight2']").each(function () {
                        if ($(this).val() == '') {
                            lw = false;
                            return false;
                        } else {
                            weight2s.push($(this).val());
                            lw = true;
                        }

                    });

                    if (!lw) {
                        Alert({msg: "请输入续重重量", type: 'error'});
                        return false;
                    }
                    _this.model.data.weight2s_str = weight2s.join("*");
                    var fee2s = new Array();
                    var lsfe = true;
                    $("input[name='fee2']").each(function () {
                        if ($(this).val() == '') {
                            lsfe = false;
                            return false;
                        } else {
                            fee2s.push($(this).val());
                            lsfe = true;
                        }

                    });
                    if (!lsfe) {
                        Alert({msg: "请输入续重运费", type: 'error'});
                        return false;
                    }
                    _this.model.data.fee2s_str = fee2s.join("*");
                }

                if (_this.model.put()) {
                    location.href = '/site/shipping';
                }
            });
        }, change: function (e) {
            this.model.data[$(e.target).attr('name')] = $(e.target).val();
        }
    };

    var set_arae = function (e, dom, region, regions) {
        var areas = new Array();
        $(".areas").each(function () {
            areas.push($(this).val());
        });
        var areas_select = ',' + areas.join(',') + ',';
        var content = template('region-tpl', {region: region, regions: regions, areas_select: areas_select});
        var area = new Array();
        dialog({
            id: 'province-list',
            content: content,
            width: 500,
            ok: function () {
                dom.parent().find('.area_lists').html('');
                $('input[name="area_id"]').each(function () {
                    if ($(this).is(':checked')) {
                        area.push($(this).attr('id'));
                        var item = '<a href="#">' + $(this).val() + '<input type="hidden" name="area_item" id="' + $(this).attr('id') + '" value="' + $(this).val() + '"/> </a> , ';
                        dom.parent().find('.area_lists').append(item);
                        dom.parent().find('.areas').val(area.join(','));
                    }
                });
            },
            cancel: function () {

            }
        }).show();
    }

    var check_add = function (weight1, fee1, weight2, fee2) {
        console.log(weight1);
        if (weight1 == '') {
            Alert({msg: "请输入首重量", type: 'error'});
            return false
        }
        if (fee1 == '') {
            Alert({msg: "请输入首运费", type: 'error'});
            return false
        }
        if (weight2 == '') {
            Alert({msg: '请输入续重', type: 'error'});
            return false
        }
        if (fee2 == '') {
            Alert({msg: "请输入续重运费", type: 'error'});
            return false
        }
        return true;
    }

    var check_type = function (dom, num) {
        var reg = /^[0-9]+(.[0-9]{0,4})?$/;
        if (num != '') {
            if (!reg.test(num)) {
                Alert({msg: "请输入数字", type: 'error'});
                dom.val("");
                dom.focus();
                return false
            }
        }

    }

    new index();

});